<?php
/**
 * Created by PhpStorm.
 * User: server
 * Date: 2019/5/23
 * Time: 10:09
 */

namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);

use app\admin\Controller;
use think\Db;
use think\Config;
use think\Request;

class DriverGoodReputation extends Controller
{

    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $data = input();
        $map = [];
        $map['dgr.status'] = 2;

        if (!empty($data['dispatch_group_id'])) {
            $map['dgr.dispatch_group_id'] = ['=', $data['dispatch_group_id']];
        }

        if (!empty($data['title'])) {
            $map['r.title'] = ['like', "%{$data['title']}%"];
        }

        if (!empty($data['realname'])) {
            $map['au.realname'] = ['like', "%{$data['realname']}%"];
        }

        if (!empty($data['bank_name'])) {
            $map['dgr.bank_name'] = ['like', "%{$data['bank_name']}%"];
        }

        if (!empty($data['card_num'])) {
            $map['dgr.card_num'] = ['like', "%{$data['card_num']}%"];
        }

        if ($data['go_date'] && $data['go_date2']) {
            $map['dtg.go_date'] = array("between", [strtotime($data['go_date'] . " 00:00:00"), strtotime($data['go_date2'] . " 23:59:59")]);
        } else {
            if ($data['go_date']) {
                $map['dtg.go_date'] = array("between", [strtotime($data['go_date'] . " 00:00:00"), strtotime($data['go_date'] . " 23:59:59")]);
            }
            if ($data['go_date2']) {
                $map['dtg.go_date'] = array("between", [strtotime($data['go_date2'] . " 00:00:00"), strtotime($data['go_date2'] . " 23:59:59")]);
            }
        }

        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");

        $list = Db::name('driver_good_reputation')
            ->alias('dgr')
            ->join('tp_dispatch_traveler_group dtg', 'dgr.dispatch_group_id=dtg.id', 'left')
            ->join('tp_admin_user au', 'dtg.driver_user_id=au.id', 'left')
            ->join('tp_route r', 'dtg.route_id=r.id', 'left')
            ->join('tp_driver d', 'dtg.driver_user_id=d.user_id', 'left')
            ->join('tp_driver_type dt', 'd.driver_type=dt.id', 'left')
            ->field('dgr.*,dgr.remark,dtg.go_date,dtg.driver_user_id,dtg.route_id,au.realname,r.title,d.accumulative_award,d.driver_type,dt.name')
            ->where($map)
            ->order('id desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $new_list = $list->toArray()['data'];

        foreach ($new_list as $k => $v) {
            $award = Db::name('driver_good_reputation')
                ->where('status', 2)
                ->sum('award');
            $new_list[$k]['accumulative_award'] = $new_list[$k]['accumulative_award'] + $award;
        }

        $this->view->assign('list', $new_list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        return $this->view->fetch();
    }

    /**
     * 电子表格
     * @return mixed
     */
    public function get_excel(Request $request)
    {
        $data = input();
        ini_set('max_execution_time', 3600);//1小时
        ini_set('memory_limit', '500M');
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel, 'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l + 65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j] . $letter[$k];
            }
        }
        $tableHeader = ['派车单号', '司机', '司机类型', '线路名称', '起始日期', '开户银行卡支行', '银行卡号', '好评奖励', '申请时间', '累计好评奖励', '备注'];
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++) {
            $export_sheet->setCellValue("$letter[$i]1", "$tableHeader[$i]");
            $export_sheet->getColumnDimension("$letter[$i]")->setWidth(20);
        }
        $map = array();

        //选择导出数据
        if ($data['id']) {
            $id = implode($data['id'], ',');
            $map['dgr.id'] = ['in', $id];
        }

        $map['dgr.status'] = 2;

        if (!empty($data['dispatch_group_id'])) {
            $map['dgr.dispatch_group_id'] = ['=', $data['dispatch_group_id']];
        }

        if (!empty($data['title'])) {
            $map['r.title'] = ['like', "%{$data['title']}%"];
        }

        if (!empty($data['realname'])) {
            $map['au.realname'] = ['like', "%{$data['realname']}%"];
        }

        if (!empty($data['bank_name'])) {
            $map['dgr.bank_name'] = ['like', "%{$data['bank_name']}%"];
        }

        if (!empty($data['card_num'])) {
            $map['dgr.card_num'] = ['like', "%{$data['card_num']}%"];
        }

        if ($data['go_date'] && $data['go_date2']) {
            $map['dtg.go_date'] = array("between", [strtotime($data['go_date'] . " 00:00:00"), strtotime($data['go_date2'] . " 23:59:59")]);
        } else {
            if ($data['go_date']) {
                $map['dtg.go_date'] = array("between", [strtotime($data['go_date'] . " 00:00:00"), strtotime($data['go_date'] . " 23:59:59")]);
            }
            if ($data['go_date2']) {
                $map['dtg.go_date'] = array("between", [strtotime($data['go_date2'] . " 00:00:00"), strtotime($data['go_date2'] . " 23:59:59")]);
            }
        }

        $list = Db::name('driver_good_reputation')
            ->alias('dgr')
            ->join('tp_dispatch_traveler_group dtg', 'dgr.dispatch_group_id=dtg.id', 'left')
            ->join('tp_admin_user au', 'dtg.driver_user_id=au.id', 'left')
            ->join('tp_route r', 'dtg.route_id=r.id', 'left')
            ->join('tp_driver d', 'dtg.driver_user_id=d.user_id', 'left')
            ->join('tp_driver_type dt', 'd.driver_type=dt.id', 'left')
            ->field('dgr.dispatch_group_id,au.realname,dt.name,r.title,dtg.go_date,dgr.bank_name,dgr.card_num,dgr.award,dgr.apply_time,d.accumulative_award,dgr.remark')
            ->where($map)
            ->order('dgr.id desc')
            ->select();

        foreach ($list as $k => $v) {

            if ($v['go_date']) {
                $list[$k]['go_date'] = date('Y-m-d H:i:s', $v['go_date']);
            }
            if ($v['apply_time']) {
                $list[$k]['apply_time'] = date('Y-m-d H:i:s', $v['apply_time']);
            }

        }
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        //定义table键
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis', time()) . "司机好评奖励-司机好评奖励数据.xls";
        $fileName = iconv('utf-8', 'gb2312', $fileName);
        ob_end_clean();
        if ($request->isGet()) {
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename=' . $fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        } else {
            // 保存文件到服务器上
            $path = ROOT_PATH . "public/excel";
            // 判断文件是否存在
            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            $fileName = iconv('gb2312', 'utf-8', $fileName);
            $file = $path . "/{$fileName}";
            $writer->save($file);
            $url = $request->domain() . "/excel/{$fileName}";
            return ajax_return_adv($url, '', '', '', '', '', 5);
        }
    }

    /**
     * 确认结算（结算成功）
     * @return mixed
     * @author 李锐志
     */
    public function confirm_settlement()
    {
        $data = input();


        if ($this->request->isAjax()) {
            // 获取该派车单的基本信息
            $info = Db::name('driver_good_reputation')
                ->alias('dgr')
                ->join('tp_dispatch_traveler_group dtg', 'dgr.dispatch_group_id=dtg.id', 'left')
                ->join('tp_driver d', 'dtg.driver_user_id=d.user_id', 'left')
                ->field('dgr.*,dtg.remark,dtg.go_date,dtg.driver_user_id,dtg.route_id,d.accumulative_award')
                ->where('dgr.id', $data['id'])
                ->find();

            // 状态修改
            $edit_flag = Db::name('driver_good_reputation')
                ->where('id', $data['id'])
                ->update([
                    'status' => 1,
                    'settlement_mode' => $data['settlement_mode'],
                    'settlement_money' => $info['award'],
                    'settlement_time' => time()
                ]);

            // 司机的好评累计奖励修改
            $accumulative_flag = Db::name('driver')
                ->where('user_id', $info['driver_user_id'])
                ->setInc('accumulative_award', $info['award']);

            if ($edit_flag && $accumulative_flag) {
                return ajax_return_adv('结算成功');
            } else {
                return ajax_return_adv_error('结算失败');
            }
        } else {

            // 获取基本信息
            $vo = Db::name('driver_good_reputation')
                ->alias('dgr')
                ->join('tp_dispatch_traveler_group dtg', 'dgr.dispatch_group_id=dtg.id', 'left')
                ->join('tp_admin_user au', 'dtg.driver_user_id=au.id', 'left')
                ->join('tp_route r', 'dtg.route_id=r.id', 'left')
                ->join('tp_driver d', 'dtg.driver_user_id=d.user_id', 'left')
                ->field('dgr.*,dtg.remark,dtg.go_date,dtg.driver_user_id,dtg.route_id,au.realname,r.title,d.accumulative_award')
                ->where('dgr.id', $data['id'])
                ->find();

            $this->view->assign('vo', $vo);
            return $this->view->fetch();
        }
    }

    /**
     * 批量结算（结算成功）
     * @return mixed
     * @author 颜东淦
     */
    public function batch_settlement()
    {
        $data = input();

        if (!isset($data['id'])) {
            return ajax_return_adv_error('没有选择派车单，请重试');
        }

        $success = 0;
        $error = 0;
        $error_id = [];

        foreach ($data['id'] as $k => $v) {
            // 获取该派车单的基本信息
            $info = Db::name('driver_good_reputation')
                ->alias('dgr')
                ->join('tp_dispatch_traveler_group dtg', 'dgr.dispatch_group_id=dtg.id', 'left')
                ->join('tp_driver d', 'dtg.driver_user_id=d.user_id', 'left')
                ->field('dgr.*,dtg.remark,dtg.go_date,dtg.driver_user_id,dtg.route_id,d.accumulative_award')
                ->where('dgr.id', $v)
                ->find();

            // 状态修改
            $edit_flag = Db::name('driver_good_reputation')
                ->where('id', $v)
                ->update([
                    'status' => 1,
                    'settlement_mode' => $data['settlement_mode'],
                    'settlement_money' => $info['award'],
                    'settlement_time' => time()
                ]);

            // 司机的好评累计奖励修改
            $accumulative_flag = Db::name('driver')
                ->where('user_id', $info['driver_user_id'])
                ->setInc('accumulative_award', $info['award']);

            if ($edit_flag && $accumulative_flag) {
                $success += 1;
            } else {
                $error += 1;
                $error_id[] = $info['dispatch_group_id'];
            }
        }
        if (count($error_id) === 0) {
            $msg = '成功结算：' . $success . '条。失败结算' . $error . "条。";
        } else {
            $temp = implode(',', $error_id);
            $msg = '成功结算：' . $success . '条。失败结算' . $error . "条。失败的派车单ID为：" . $temp . "。";
        }
        return ajax_return_adv($msg);
    }

    /**
     * 驳回结算
     * @return mixed
     */
    public function refuse_settlement()
    {
        $data = input();

        if ($this->request->isAjax()) {

            // 状态修改
            $result = Db::name('driver_good_reputation')
                ->where('id', $data['id'])
                ->update([
                    'status' => 0,
                    'reject_remark' => $data['reject_remark'],
                    'reject_time' => time()
                ]);

            if ($result) {
                return ajax_return_adv('驳回成功');
            } else {
                return ajax_return_adv_error('驳回失败');
            }

        } else {

            // 获取基本信息
            $vo = Db::name('driver_good_reputation')
                ->alias('dgr')
                ->join('tp_dispatch_traveler_group dtg', 'dgr.dispatch_group_id=dtg.id', 'left')
                ->join('tp_admin_user au', 'dtg.driver_user_id=au.id', 'left')
                ->join('tp_route r', 'dtg.route_id=r.id', 'left')
                ->join('tp_driver d', 'dtg.driver_user_id=d.user_id', 'left')
                ->field('dgr.*,dtg.remark,dtg.go_date,dtg.driver_user_id,dtg.route_id,au.realname,r.title,d.accumulative_award')
                ->where('dgr.id', $data['id'])
                ->find();

            $this->view->assign('vo', $vo);
            return $this->view->fetch();
        }
    }

    /**
     * 批量驳回
     * @return mixed
     * @author 颜东淦
     */
    public function batch_refuse()
    {
        $data = input();

        if (!isset($data['id'])) {
            return ajax_return_adv_error('没有选择派车单，请重试');
        }

        $success = 0;
        $error = 0;
        $error_id = [];

        foreach ($data['id'] as $k => $v) {
            $dispatch_group_id = Db::name('driver_good_reputation')
                ->where('id', $v)
                ->value('dispatch_group_id');

            // 状态修改
            $result = Db::name('driver_good_reputation')
                ->where('id', $v)
                ->update([
                    'status' => 0,
                    'reject_remark' => $data['reject_remark'],
                    'reject_time' => time()
                ]);

            if ($result) {
                $success += 1;
            } else {
                $error += 1;
                $error_id[] = $dispatch_group_id;
            }
        }
        if (count($error_id) === 0) {
            $msg = '成功驳回：' . $success . '条。失败驳回' . $error . "条。";
        } else {
            $temp = implode(',', $error_id);
            $msg = '成功驳回：' . $success . '条。失败驳回' . $error . "条。失败的派车单ID为：" . $temp . "。";
        }
        return ajax_return_adv($msg);
    }
}